package cn.itcast.client;

import cn.itcast.message.*;
import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProcotolFrameDecoder;
import cn.itcast.server.session.SessionFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        // 信号量，等待服务端响应登录请求
        CountDownLatch cdl = new CountDownLatch(1);
        // 标志，是否登陆成功，初始值为 false
        AtomicBoolean flag = new AtomicBoolean();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    //写监测，限定时间后触发
                    ch.pipeline().addLast(new IdleStateHandler(0,
                                                    3,0));
                    //处理写监测
                    ch.pipeline().addLast(new ChannelDuplexHandler(){
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            ctx.channel().writeAndFlush(new PingMessage());
                        }
                    });
                    // 主业务
                    ch.pipeline().addLast("client handler",new ChannelInboundHandlerAdapter(){
                        // 连接建立后触发
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // 另起线程异步处理用户登录
                            new Thread(() -> {
                                Scanner sc = new Scanner(System.in);
                                System.out.println("请输入用户名：");
                                String username = sc.nextLine();
                                System.out.println("请输入密码：");
                                String password = sc.nextLine();
                                LoginRequestMessage loginMessage = new LoginRequestMessage(username, password);
                                ctx.writeAndFlush(loginMessage);

                                // 阻塞
                                try {
                                    cdl.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if(!flag.get()){
                                    //通道关闭
                                    ctx.channel().close();
                                    return;
                                }
                                // 登录成功
                                loop:
                                while(true){
                                    System.out.println("==================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");
                                    String choice = sc.nextLine();
                                    String[] slice = choice.split(" ");
                                    switch (slice[0]){
                                        case "send":
                                            //私聊
                                            ctx.writeAndFlush(new ChatRequestMessage(username, slice[1], slice[2]));
                                            break;
                                        case "gsend":
                                            // 向群聊发送信息
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, slice[1], slice[2]));
                                            break;
                                        case "gcreate":
                                            // 建群
                                            Set members = new HashSet(Arrays.asList(slice[2].split(",")));
                                            members.add(username);
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(slice[1], members));
                                            break;
                                        case "gmembers":
                                            // 获取群聊成员
                                            break;
                                        case "gjoin":
                                            // 加入群聊
                                            break;
                                        case "gquit":
                                            // 退群
                                            break;
                                        case "quit":
                                            // 退出登录
                                            ctx.channel().close();
                                            break loop; // 退出循环，结束线程
                                    }
                                }

                            },"client input").start();
                        }

                        // 接收到服务端响应后的处理
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if((msg instanceof LoginResponseMessage)){
                                LoginResponseMessage message = (LoginResponseMessage) msg;
                                if (message.isSuccess()) {
                                    log.debug("message ==> {}", message.getReason());
                                    flag.set(true);
                                }
                            }
                            // 唤醒阻塞线程
                            cdl.countDown();

                        }

                        // 用户通道请求正常关闭
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            //解绑
                            SessionFactory.getSession().unbind(ctx.channel());
                            log.error("通道 {} 已关闭！", ctx.channel());
                        }

                        // 用户通道异常关闭
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            //解绑
                            SessionFactory.getSession().unbind(ctx.channel());
                            log.error("通道 {} 异常关闭，异常：{}", ctx.channel(), cause.getMessage());
                        }
                    });

                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
